import {
  Breadcrumb,
  Button,
  Image,
  Input,
  Popconfirm,
  Space,
  Table,
  Upload as Uploader,
  UploadProps,
} from "antd";
import React, { useEffect, useState } from "react";
import { uploadApi } from "../../../../utils/backend/server";
import styles from "./Upload.module.css";
import { UPLOAD_RESOURCE } from "../../../../utils/utils/request";
import { HomeOutlined, InboxOutlined, UploadOutlined } from "@ant-design/icons";
import { formatDate } from "../../../../utils/common/formatTime";
import { toast } from "../../../../components/Toast/Toast";
import { useAppDispatch, useAppSelector } from "../../../../utils/store/hooks";
import {
  updateCutBoard,
  updatePageInfo,
} from "../../../../utils/store/uploadSlice";
import { VideoPreview } from "./PreviewVideo/PreviewVideo";

const MB = 1024 * 1024;
const KB = 1024;

export type UploadFileType = {
  filename: string;
  path: string;
  size: number;
  lastModified: number;
  isDirectory: boolean;
};
export type PathItem = {
  path: string;
  title: React.ReactNode | string;
  index: number;
};

export type MoveFileType = {
  from: string;
  to: string;
};
const convertPathArr = (path: PathItem[], extra = "") =>
  path.map((item) => item.path).join("/") +
  (extra.startsWith("/") ? extra : `/${extra}`);

export default () => {
  const delFiles = async (names: string[]) => {
    await uploadApi.delUploadFiles(
      names.map((val) => convertPathArr(path, val))
    );

    toast("delete success");
    setSelection([]);
    // for (let i = 0; i < names.length; i++) {
    //   const { success } = await uploadApi.delUploadFile(
    //     convertPathArr(path, names[i])
    //   );
    //   if (!success) toast("delete fail: " + names[i]);
    // }
    refresh();
  };

  // const delFiles = async (names: string[]) => {
  //   for (let i = 0; i < names.length; i++) {
  //     const { success } = await uploadApi.delUploadFile(
  //       convertPathArr(path, names[i])
  //     );
  //     if (!success) toast("delete fail: " + names[i]);
  //   }
  //   refresh();
  // };

  const columns = [
    {
      title: "Name",
      dataIndex: "filename",
      key: "filename",
    },
    {
      title: "preview",
      dataIndex: "preview",
      key: "preview",
      render: (_: any, record: UploadFileType) => {
        const url =
          UPLOAD_RESOURCE.slice(0, UPLOAD_RESOURCE.length - 1) +
          convertPathArr(path, record.filename);
        return (
          <div>
            {record.filename.endsWith(".mp4") && <VideoPreview url={url} />}

            {(record.filename.endsWith(".jpg") ||
              record.filename.endsWith(".png")) && (
              //  className={styles.preview}
              <Image width={50} preview src={url} />
            )}
          </div>
        );
      },
    },
    {
      title: "Size",
      dataIndex: "size",
      key: "size",
      render: (size: number) => {
        let formatSize: string = "";
        if (size > MB) {
          formatSize = Math.floor(size / MB) + "MB";
        } else if (size > KB) {
          formatSize = Math.floor(size / KB) + "KB";
        } else {
          formatSize = size + "BYTE";
        }
        return <div>{formatSize}</div>;
      },
    },
    {
      title: "Last modified time",
      dataIndex: "lastModified",
      key: "lastModified",
      render: (row: string) => {
        return <div>{`${formatDate(row, true)}`}</div>;
      },
    },
    {
      title: "Action",
      key: "action",
      fixed: "right" as const,
      render: (_: any, record: UploadFileType) => (
        <Space>
          {record.isDirectory ? (
            <Button
              onClick={() => {
                setPath((e) => [
                  ...e,
                  {
                    path: record.filename,
                    title: record.filename,
                    index: e.length,
                  },
                ]);
                dispatch(
                  updatePageInfo({
                    pageNo: 1,
                  })
                );
              }}
              type="primary"
            >
              Enter
            </Button>
          ) : (
            <>
              {/* <a
                href={
                  UPLOAD_RESOURCE.slice(0, UPLOAD_RESOURCE.length - 1) +
                  convertPathArr(path, record.filename)
                }
                target="_blank"
              >
                preview
              </a> */}
              <a
                href={uploadApi.download(convertPathArr(path, record.filename))}
                download={record.filename}
                target="_blank"
              >
                download
              </a>
              {/* <a onClick={() => delFile(record)}>Delete</a> */}
            </>
          )}
          {/* <Popconfirm
            title="Delete the file?"
            description="Are you sure to delete this file?"
            onConfirm={() => delFile(record)}
            okText="Yes"
            cancelText="No"
          >
            <Button danger>Delete</Button>
          </Popconfirm> */}
        </Space>
      ),
    },
  ];

  const [dataSource, setDataSource] = useState<UploadFileType[]>();

  const [path, setPath] = useState<PathItem[]>([
    {
      path: "",
      title: <HomeOutlined />,
      index: 0,
    },
  ]);

  const [selection, setSelection] = useState<string[]>([]);
  // const setPath = (newPath: PathItem) => {
  //   // newPath.onClick = (e) => redirect(e);
  //   _setPath((e) => {
  //     const ret = [...e, newPath];
  //     // console.log(ret, "ret");

  //     return ret;
  //   });
  //   refresh();
  // };

  const dispatch = useAppDispatch();
  const uploadStore = useAppSelector((state) => state.upload);
  const refresh = async () => {
    const { total, data } = await uploadApi.getUploadList(
      convertPathArr(path),
      uploadStore.pageInfo.pageNo,
      uploadStore.pageInfo.pageSize
    );
    // .then((data) => {
    setDataSource(data.map((val) => ({ ...val, key: val.filename })));
    dispatch(
      updatePageInfo({
        total,
      })
    );
    // });
  };

  useEffect(() => {
    refresh();
  }, [path, uploadStore.pageInfo.pageNo]);

  const props: UploadProps = {
    action: uploadApi.upload(),
    multiple: true,
    data: {
      path: convertPathArr(path),
    },
    headers: {
      Authorization: `Bearer ${localStorage.getItem("Authorization")}`,
    },
    onChange({ file, fileList }) {
      if (file.status !== "uploading") {
        refresh();
      }
    },
    defaultFileList: [],
  };

  // const clearUpload = () => {
  //   uploadApi.clearUpload().then(() => {
  //     message.success("clear success");
  //     refresh();
  //   });
  // };

  const [dirName, setDirName] = useState("");
  return (
    <>
      <div className={styles.drag}>
        <div className={styles.header}>
          <div className={styles["mb-20"]}>
            <Breadcrumb
              items={path}
              itemRender={(record) => {
                return (
                  <div
                    onClick={() => {
                      // console.log(record, "record");
                      setPath((e) => {
                        return e.slice(0, (record as PathItem).index + 1);
                      });
                      dispatch(
                        updatePageInfo({
                          pageNo: 1,
                          total: 0,
                        })
                      );
                    }}
                    className={styles.link}
                  >
                    {record.title}
                  </div>
                );
              }}
            />
          </div>
          <Space className={styles["mb-20"]}>
            <Input
              value={dirName}
              onChange={(e) => setDirName(e.target.value)}
            />
            {
              <>
                {selection.length === 0 && (
                  <Button
                    onClick={async () => {
                      if (dirName === "")
                        return toast("dir name can not be empty");
                      const res = await uploadApi.createFolder(
                        convertPathArr(path, dirName)
                      );

                      toast(res.msg);
                      setDirName("");
                      refresh();
                    }}
                    type="primary"
                  >
                    mkdir
                  </Button>
                )}
                {selection.length === 1 && (
                  <Button
                    onClick={async () => {
                      if (dirName === "") return toast("name can not be empty");
                      const res = await uploadApi.rename({
                        from: convertPathArr(path, selection[0]),
                        to: convertPathArr(path, dirName),
                      });
                      setDirName("");
                      setSelection([]);
                      refresh();
                    }}
                    type="primary"
                  >
                    rename
                  </Button>
                )}
              </>
            }
            <Button onClick={refresh} type="primary">
              refresh
            </Button>
          </Space>
        </div>
        <div className={styles.operation}>
          {selection.length > 0 && (
            <Space>
              <Popconfirm
                title="Delete the file?"
                description="Are you sure to delete this file?"
                onConfirm={() => delFiles(selection)}
                okText="Yes"
                cancelText="No"
              >
                <Button danger>Delete</Button>
              </Popconfirm>
              <Button
                onClick={() => {
                  dispatch(
                    updateCutBoard(
                      selection.map((val) => {
                        return {
                          path,
                          name: val,
                        };
                      })
                    )
                  );
                  setSelection([]);
                }}
                type="primary"
              >
                Cut
              </Button>
              <Button
                type="link"
                onClick={() => {
                  setSelection([]);
                }}
              >
                Cancel
              </Button>
            </Space>
          )}
          {uploadStore.cutBoard.length > 0 && (
            <Space>
              <Button
                type="link"
                onClick={async () => {
                  await uploadApi.pasteFiles(
                    uploadStore.cutBoard.map((oldFile) => {
                      return {
                        from: convertPathArr(oldFile.path, oldFile.name),
                        to: convertPathArr(path, oldFile.name),
                      };
                    })
                  );

                  dispatch(updateCutBoard([]));

                  refresh();
                }}
              >
                Paste
              </Button>

              <Button type="link" onClick={() => dispatch(updateCutBoard([]))}>
                Cancel
              </Button>
            </Space>
          )}
        </div>
      </div>
      <div className={styles.space}>
        <Table
          dataSource={dataSource}
          pagination={{
            current: uploadStore.pageInfo.pageNo,
            pageSize: uploadStore.pageInfo.pageSize,
            total: uploadStore.pageInfo.total,
            onChange: (page) => {
              dispatch(
                updatePageInfo({
                  pageNo: page,
                  total: 0,
                })
              );
            },
          }}
          rowSelection={{
            type: "checkbox",
            selectedRowKeys: selection,
            onChange: (selectedRowKeys: React.Key[]) => {
              setSelection(selectedRowKeys as string[]);
            },
          }}
          columns={columns}
          scroll={{ x: 1000 }}
          virtual
        />
      </div>

      <div className={styles.drag}>
        <Uploader {...props}>
          <Button icon={<UploadOutlined />} type="primary">
            Upload
          </Button>
        </Uploader>
      </div>
    </>
  );
};
